class Solution(object):
    def countSubIslands(self, grid1, grid2):
        m = len(grid1)
        n = len(grid1[0])
        ans = 0
        for i in range(m):
            for j in range(n):
                if grid2[i][j] == 1:
                    grid2[i][j] = 0
                    a = {(i, j)}
                    now = {(i, j)}
                    while now:
                        x, y = now.pop()
                        for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                            if 0 <= ux < m and 0 <= uy < n:
                                if grid2[ux][uy] and (ux, uy) not in a:
                                    grid2[ux][uy] = 0
                                    a.add((ux, uy))
                                    now.add((ux, uy))
                    flag = True
                    for x, y in a:
                        if not grid1[x][y]:
                            flag = False
                            break
                    if flag:
                        ans += 1
        return ans


